<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Circle;
use app\common\model\circle\Admin;
use app\common\model\circle\Apply;
use app\common\model\circle\Ban;
use app\common\model\circle\Cate;
use app\common\model\circle\Level;
use app\common\model\circle\Liyou;
use app\common\model\circle\Notice;
use app\common\model\circle\User as CircleUser;
use app\common\model\circle\Log as CircleLog;
use app\common\model\publics\Report;
use app\common\model\publics\Reportlog;
use app\common\model\publics\Likecoll;
use app\common\model\trends\Cate2;
use app\common\model\trends\Cate as TrendsCate;
use app\common\model\trends\TrendsComment;
use app\common\model\Trends;
use EasyWeChat\Foundation\Application;
use fast\Date;
use think\Config;
use think\Db;

/**
 * 圈子信息接口
 */
class Circles extends Api
{
	//protected $connection = 'database.db_second';//连接配置
	protected $noNeedLogin = ['CircleAdmin','my_circle','group_info','circle_cate'];
	protected $noNeedRight = ['*'];

	public function _initialize()
	{
		parent::_initialize();
		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);
		$circleuser = CircleUser::where(['user_id' => $user_id, 'circle_id' => $circle_id])->find();
		if ($circle_id > 0) {
			$circle = Circle::get($circle_id);
			if (!$circle) {
				$this->success('圈子不存在', [], 2);
			}

			if ($circle->user_id != $user_id) {
				if (!$circleuser) {
					$this->success('无权限', [], 2);
				}
				if ($circleuser->identity > 2) {
					$this->success('无权限', [], 2);
				}
			}
		}
	}

	/**
	 * 圈子分类
	 */
	public function circle_cate()
	{
		$list = Cate::order('weigh desc')->select();
		$this->success("", $list);
	}

	/**
	 * 圈子列表
     * 
	 * @ApiMethod (POST)
	 * @param string $title  圈子名称
	 * @param int $cate_id 分类id
	 * @param int $page 当前页码
	 * @param int $count 每页数量
	 */
	public function circle_list()
	{
		$user_id = $this->auth->id;
		$title   = $this->request->post('title', '');
		$cate_id = $this->request->post('cate_id', 0);
		$page    = $this->request->post('page', 1);
		$count   = $this->request->post('count', 10);

		$where           = [];
		$where['status'] = 2;
		if ($cate_id) {
			$where['circlecate_id'] = $cate_id;
		}
		if ($title) {
			$where['name'] = ['like', "%$title%"];
		}

		$list = \app\common\model\Circle::where($where)
		                                ->order('id desc')
		                                ->paginate($count, false, ["page" => $page]);
		$this->success("", $list);
	}

	/**
	 * 我的圈子
	 */
	public function my_circle()
	{
		$user_id = $this->auth->id;
		//$user_id = 146169; //test
		$where                      = [];
		$where['user.user_id']      = $user_id;
		$where['user.identity']     = ['in', '1,2,3'];
		$where['circle.status']     = 2;
		$where['circle.deletetime'] = null;

		$list = \app\common\model\circle\User::with(['circle'])
		                                     ->where($where)
		                                     ->order("role asc,id desc")
		                                     ->select();
		foreach ($list as $row) {
			$row->visible(['id', 'user_id', 'circle_id', 'circle_id', 'circle', 'role']);
			$row->getRelation('circle')->visible(['id', 'user_id', 'logo_image', 'name']);
		}
		$this->success("", $list);
	}

	/**
	 * 修改加入方式
     * 
	 * @ApiMethod (POST)
	 * @param string $title  加入理由
	 * @param int $circle_id 圈子id
	 * @param int $join_state 加入状态:1=直接加入,2=点击加入,3=申请加入,4=答题加入
	 * @param int $is_img  提供图片:1=是,2=否
	 */
	public function save_join()
	{
		$user_id    = $this->auth->id;
		$circle_id  = $this->request->post('circle_id', 0);
		$join_state = $this->request->post('join_state');
		$title      = $this->request->post('title', '');
		$is_img     = $this->request->post('is_img', 2);

		$circle = Circle::get($circle_id);

		if (!$circle) {
			$this->success('圈子信息不存在', [], 2);
		}
		if (!$join_state) {
			$this->success('参数错误', [], 2);
		}

		if ($join_state == 3) {

			if (!$title) {
				$this->success('请输入理由提示文案', [], 2);
			}

			$liyou = Liyou::where(['circle_id' => $circle_id])->find();
			if ($liyou) {
				$liyou->save(['title' => $title, 'is_img' => $is_img]);
			} else {
				Liyou::create(['circle_id' => $circle_id, 'title' => $title, 'is_img' => $is_img, 'createtime' => time()]);
			}

		}

		$res = $circle->save(['join_state' => $join_state, 'updatetime' => time()]);

		if ($res) {
			$this->success('成功');
		} else {
			$this->success('失败', [], 2);
		}
	}

	/**
	 * 审核圈友
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 * @param string $apply_ids  申请人id（多个id用,分隔）
	 * @param int $state  状态（状态:1=申请中,2=已通过,3=已拒绝）
	 */
	public function apply_lairage()
	{
		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);
		$apply_ids = $this->request->post('apply_ids', '');
		$state     = $this->request->post('state', 0);

		if (empty($apply_ids) || empty($state) || empty($circle_id)) {
			$this->success('参数错误', [], 2);
		}

//		$circle = \app\common\model\circle\User::where(['user_id'=>$user_id,'circle_id'=>$circle_id])->find();
//
//		if(!$circle){
//
//			$this->success('无权限',[],2);
//		}
//		if($circle->identity > 2){
//			$this->success('无权限',[],2);
//		}

		$list = explode(',', $apply_ids);

		Db::startTrans();
		$arr = [];
		foreach ($list as $v) {

			$apply = Apply::where(['id' => $v, 'circle_id' => $circle_id, 'state' => 1])->find();
			if ($apply) {
				$arr[] = $apply->save(['state' => $state, 'updatetime' => time()]);
				if ($state == 2) {
					$circleuser = \app\common\model\circle\User::where(['user_id' => $apply->user_id, 'circle_id' => $apply->circle_id])->find();
					if (!$circleuser) {

						//$arr[] = Db::name('circle_user')->insert(['user_id' => $apply->user_id, 'circle_id' => $apply->circle_id, 'createtime' => time()]);
						$arr[] = \app\common\model\circle\User::insert(['user_id' => $apply->user_id, 'circle_id' => $apply->circle_id, 'createtime' => time()]);
						//初次加入圈子经验奖励
						exps($apply->circle_id, $user_id, 1);
					}

				}
			}

		}

		if (in_array(false, $arr)) {
			Db::startTrans();
			$this->error("出差了");
		} else {
			Db::commit();
			$this->success('审核成功');
		}

	}

	/**
	 * 圈子申请列表
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 * @param int $state  状态（状态:1=申请中,2=已通过,3=已拒绝）
	 * @param int $page 当前页码
	 * @param int $count 每页数量
	 */
	public function lairage_list()
	{

		$circle_id = $this->request->post('circle_id', 0);
		$state     = $this->request->post('state', 0);
		$page      = $this->request->post('page', 1);
		$count     = $this->request->post('count', 10);

		if (!$circle_id) {
			$this->success('参数错误', [], 2);
		}

		$where              = [];
		$where['circle_id'] = $circle_id;
		if ($state) {
			$where['state'] = $state;
		}

		$list = Apply::where($where)->order('id desc')
		             ->paginate($count, false, ["page" => $page]);

		$this->success("", $list);

	}

	/**
	 * 管理员申请列表
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 * @param int $page 当前页码
	 * @param int $count 每页数量
	 */
	public function admin_list()
	{
		$circle_id = $this->request->post('circle_id', 0);
		$page  = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);

		if (!$circle_id) {
			$this->success('参数错误', [], 2);
		}

		$where              = [];
		$where['circle_id'] = $circle_id;
		$where['type']      = 2;

		$list = Admin::where($where)->order('id desc')
		             ->paginate($count, false, ["page" => $page]);

		$this->success("", $list);

	}

	/**
	 * 审核管理员
	 *  
	 * @ApiMethod (POST)
	 * @param int $type  申请角色: 1=吧主申请,2=管理员申请
	 * @param int $circle_id 圈子id
	 * @param int $state  状态: 1=申请中,2=已通过,3=已拒绝
	 * @param string $apply_ids  申请人id（多个id用,分隔）
	 */
	public function admin_apply()
	{

		$user_id   = $this->auth->id;
		$type      = $this->request->post('type', 1);
		$circle_id = $this->request->post('circle_id', 0);
		$apply_ids = $this->request->post('apply_ids', '');
		$state     = $this->request->post('state', 0);

		if (empty($apply_ids) || empty($state) || empty($circle_id)) {
			$this->success('参数错误', [], 2);
		}

		$admin = Admin::where(['id' => $apply_ids, 'type' => 2, 'circle_id' => $circle_id, 'status' => 1])->find();

		if (!$admin) {
			$this->success('信息不存在', [], 2);
		}

		$circleuser = CircleUser::where(['circle_id' => $circle_id, 'user_id' => $admin->user_id, 'identity' => ['in', '1,2,3']])->find();

		if (!$circleuser) {
			$this->success('圈友不存在', [], 2);
		}
		if ($circleuser->identity < 3) {
			$this->success('该圈友已经是管理员了', [], 2);
		}

		$res = $admin->save(['status' => $state, 'apply_time' => time()]);

		if ($res) {
			if ($state == 2) {
				//更改成管理员身份
				$circleuser->save(['identity' => 2]);
			} else {
				//发送系统消息
				send($user_id, $admin->user_id, 5, $admin->id, 3);
			}

			$this->success('审核成功');

		} else {
			$this->error("出差了");
		}

	}

	/**
	 * 级别列表
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 */
	public function level()
	{

		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);

		$where                    = [];
		$where['level.circle_id'] = $circle_id;

		$list = Level::with(['publiclevel'])
		             ->where($where)
		             ->order('level asc')
		             ->select();

		foreach ($list as $row) {
			$row->visible(['id', 'circle_id', 'nickname', 'level', 'createtime']);
			$row->visible(['publiclevel']);
			$row->getRelation('publiclevel')->visible(['name', 'weigh']);
		}

		$this->success('成功', $list);

	}

	/**
	 * 更改圈子级别昵称
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 * @param string|array $list  级别名称
	 */
	public function save_level()
	{
		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);
		$list      = $this->request->post('list', []);
		$list = json_decode(html_entity_decode($list), true);
		Db::startTrans();
		$arr = [];
		if (count($list) > 0) {

			foreach ($list as $k => $v) {

				$level = Level::where(['circle_id' => $circle_id, 'level' => $v['weigh']])->find();
				if ($level) {
					$arr[] = $level->save(['nickname' => $v['nickname'], 'updatetime' => time()]);
				}

			}

		} else {
			$this->error("参数错误");
		}

		if (in_array(false, $arr)) {
			Db::startTrans();
			$this->error("出差了");
		} else {
			Db::commit();
			$this->success('成功');
		}

	}

	/**
	 * 圈友管理层
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 */
	public function CircleAdmin()
	{

		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);

		$data = [];
		//吧主
		$list = CircleUser::where(['circle_id' => $circle_id, 'identity' => 1, 'role' => 2])->select();

		if ($list) {
			$data['list1'] = $list;
		} else {
			$data['list1'] = CircleUser::where(['circle_id' => $circle_id, 'identity' => 1, 'role' => 1])->select();
		}

		//管理员
		$data['list2'] = CircleUser::where(['circle_id' => $circle_id, 'identity' => 2])->select();

		$this->success("", $data);
	}

	/**
	 * 圈友列表
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 * @param string $title  查询内容
	 * @param int $page   当前页码
	 * @param int $count  每页数量
	 */
	public function CircleFriends()
	{
		$title     = $this->request->post('title', '');
		$circle_id = $this->request->post('circle_id', 0);
		//$status = $this->request->post('state', 0);
		$page  = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);

		if (!$circle_id) {
			$this->success('参数错误', [], 2);
		}

		$where = [];
		$orWhere = [];
		if ($title) {
			$orWhere['users.nickname'] = ["like", "%$title%"];
			$orWhere['users.number'] = ["like", "%$title%"];
		}

		$where['circle_id'] = $circle_id;
		if ($title) {
			$where['identity'] = ['in', '1,2,3'];
		} else {
			$where['identity'] = 3;
		}

		$where['is_auth'] = 1;
		$where['is_ban']  = 2;

		//$list = CircleUser::with(['users'])->where($where)
		//									->order('id desc')
		//                                    ->paginate($count, false, ["page" => $page]);
		$list = CircleUser::where($where)->order('id desc')->paginate($count, false, ["page" => $page]);
		if ($title) {
			$list = CircleUser::where($where)->order('id desc')->paginate($count, false, ["page" => $page]);
			//过滤nickname 或者 number 待处理
		}

		/*foreach ($list as $row) {
			$row->visible(['id', 'user_id', 'circle_id', 'identity', 'level', 'is_auth', 'is_ban', 'createtime']);
			$row->visible(['users']);
			$row->getRelation('users')->visible(['nickname']);
			$row->getRelation('users')->visible(['number']);
		}*/

		$this->success("", $list);
	}

	/**
	 * 管理圈友
	 *  
	 * @ApiMethod (POST)
	 * @param int $type   操作类型 （1移出圈子，2互动封禁，3移出加入黑名单，4设为管理员，5设为吧主，6降为圈友）
	 * @param int $circle_id 圈子id，必填
	 * @param int $user_id   用户id，必填
	 * @param int $ban_day   解禁天数
	 * @param int $memo     封禁原因
	 */
	public function SaveFriends()
	{
		$user_id   = $this->auth->id;
		$type      = $this->request->post('type', 0);   //1移出圈子2互动封禁3移出加入黑名单4设为管理员5设为吧主6降为圈友
		$user2_id  = $this->request->post('user_id', 0);//用户的
		$circle_id = $this->request->post('circle_id', 0);

		$ban_day = $this->request->post('ban_day', 0);
		$memo    = $this->request->post('memo', "");

		if (empty($user2_id) || empty($circle_id)) {
			$this->success('参数错误', [], 2);
		}

		//管理圈友
		$usercircle = CircleUser::where(['user_id' => $user2_id, 'circle_id' => $circle_id, 'is_auth' => 1])->find();

		if (!$usercircle) {
			$this->success('圈友状态异常', [], 2);
		}

		if ($type == 1) {//移出圈子

			$res = $usercircle->delete();

		} else if ($type == 2) {//互动封禁

			if ($usercircle->is_ban == 1) {
				$this->success('操作成功');
			}
			if ($ban_day <= 0) {
				$this->success('请选择解禁天数', [], 2);
			}

			$res = $usercircle->save(['is_ban' => 1, 'updatetime' => time()]);
			//添加封禁记录

			//Db::name('circle_ban')->insert([
			\app\common\model\circle\Ban::insert([
				                               'type'          => 1,
				                               'circle_id'     => $circle_id,
				                               'circleuser_id' => $usercircle->id,
				                               'user_id'       => $usercircle->user_id,
				                               'adminuser_id'  => $user_id,
				                               'day'           => $ban_day,
				                               'end_time'      => strtotime("$ban_day day"),
				                               'memo'          => $memo,
				                               'create_time'   => time(),
			                               ]);

		} else if ($type == 3) {//移出加入黑名单

			if ($usercircle->is_auth == 2) {
				$this->success('操作成功');
			}

			$res = $usercircle->save(['is_auth' => 2, 'identity' => 0, 'updatetime' => time()]);
			//添加拉黑记录
			//Db::name('circle_ban')->insert([
			\app\common\model\circle\Ban::insert([
				                               'type'          => 2,
				                               'circle_id'     => $circle_id,
				                               'circleuser_id' => $usercircle->id,
				                               'user_id'       => $usercircle->user_id,
				                               'adminuser_id'  => $user_id,
				                               'create_time'   => time(),
			                               ]);

		} else if ($type == 4) {//设为管理员

			//$res = $usercircle->save(['identity'=>2,'updatetime'=>time()]);
			//添加管理员申请
			//$apply = Db::name('circle_admin')->where(['user_id' => $user2_id, 'type' => 2, 'circle_id' => $circle_id, 'status' => 1])->find();
			$apply = \app\common\model\circle\Admin::where(['user_id' => $user2_id, 'type' => 2, 'circle_id' => $circle_id, 'status' => 1])->find();
			if ($apply) {
				$this->success('申请已提交 无需重新申请...', [], 2);
			}

			//$res = Db::name('circle_admin')->insert(['ciecle_user_id' => $user_id, 'user_id' => $user2_id, 'type' => 2, 'circle_id' => $circle_id, 'status' => 1, 'createtime' => time()]);
			$res = \app\common\model\circle\Admin::insert(['ciecle_user_id' => $user_id, 'user_id' => $user2_id, 'type' => 2, 'circle_id' => $circle_id, 'status' => 1, 'createtime' => time()]);
			if ($res) {
				$this->success('申请提交成功');
			} else {
				$this->error('出差了');
			}

		} else if ($type == 5) {//设为吧主
			//$res = $usercircle->save(['identity'=>1,'updatetime'=>time()]);
			//添加吧主申请
			//$apply = Db::name('circle_admin')->where(['user_id' => $user2_id, 'type' => 1, 'circle_id' => $circle_id, 'status' => 1])->find();
			$apply = \app\common\model\circle\Admin::where(['user_id' => $user2_id, 'type' => 1, 'circle_id' => $circle_id, 'status' => 1])->find();
			if ($apply) {
				$this->success('申请已提交 无需重新申请...', [], 2);
			}
			//$res = Db::name('circle_admin')->insert(['ciecle_user_id' => $user_id, 'user_id' => $user2_id, 'type' => 1, 'circle_id' => $circle_id, 'status' => 1, 'createtime' => time()]);
			$res = \app\common\model\circle\Admin::insert(['ciecle_user_id' => $user_id, 'user_id' => $user2_id, 'type' => 1, 'circle_id' => $circle_id, 'status' => 1, 'createtime' => time()]);
			if ($res) {
				$this->success('申请提交成功');
			} else {
				$this->error('出差了');
			}
		} else if ($type == 6) {//设为圈友
			$res = $usercircle->save(['identity' => 3, 'updatetime' => time()]);
		}

		if ($res) {
			//记录圈子日志
			circlelog(1, $user_id, $user2_id, $circle_id, 0, $type);
			$this->success('操作成功');

		} else {
			$this->error('出差了');
		}
	}

    /**
	 * 批量移出
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id，必填
	 * @param string $ids   用户id (多个id用 , 分隔)
	 */
	public function yichu()
	{
		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);
		$ids       = $this->request->post('ids', '');

		if (empty($ids)) {
			$this->success('参数错误', [], 2);
		}

		$where              = [];
		$where['user_id']   = ['in', $ids];
		$where['circle_id'] = $circle_id;

		$list = CircleUser::where($where)->select();

		Db::startTrans();
		$arr = [];

		foreach ($list as $k => $v) {

			$arr[] = $v->delete();
		}

		if (in_array(false, $arr)) {

			Db::startTrans();

			$this->error("出差了");
		} else {

			Db::commit();

			$this->success('成功');
		}

	}

	/**
	 * 圈友违规处理列表
	 *  
	 * @ApiMethod (POST)
	 * @param int $type    举报类型:1=动态举报,2=圈友举报,3=吧主举报,4=管理员举报
	 * @param int $circle_id  圈子id
	 * @param int $state    审核状态:1=举报待处理,2=申诉待处理,3=举报已处理,4=申诉已处理
	 * @param int $page    当前页码
	 * @param int $count   每页数量
	 */
	public function Violation()
	{
		$user_id   = $this->auth->id;
		$type      = $this->request->post('type', 0);
		$circle_id = $this->request->post('circle_id', 0);
		$state     = $this->request->post('state', 0);//1=举报待处理,2=申诉待处理,3=举报已处理,4=申诉已处理
		$page      = $this->request->post('page', 1);
		$count     = $this->request->post('count', 10);

		//管理员身份
//	     $circle = \app\common\model\circle\User::where(['user_id'=>$user_id,'circle_id'=>$circle_id,'is_auth'=>1])->find();
//	     if(!$circle){
//		     $this->success('无权限',[],2);
//	     }
//	     if($circle->identity > 2){
//		     $this->success('无权限',[],2);
//	     }

		$where = [];
		if ($type == 1) {
			$where['type'] = $type;
		} else {
			$where['type'] = ['in', '2,3,4'];
		}

		$where['circle_id'] = $circle_id;
		if ($state) {
			$where['state'] = $state;
		}

		$list = Report::where($where)->order('id desc')->paginate($count, false, ["page" => $page]);

		foreach ($list as $row) {
			//$row->visible(['id','type','circle_id','trends_id','yuanyin','describe','ss_describe','user','jbuser','trends']);
			//$row->visible(['id', 'type', 'circle_id', 'trends_id', 'yuanyin', 'describe', 'ss_describe', 'state', 'jb_state', 'ss_state', 'user', 'jbuser', 'trends']);
			//$row->getRelation('user')->visible(['nickname', 'avatar']);
			//$row->getRelation('jbuser')->visible(['nickname', 'avatar']);
			//$row->user->avatar   = cdnurl($row->user->avatar, true);
			//$row->jbuser->avatar = cdnurl($row->jbuser->avatar, true);
			$user = \app\common\model\User::where(['id'=>$row->user_id])->find();
		    if($user) {
		        $row->user = $user;
		    }
		    $jbuser = \app\common\model\User::where(['id'=>$row->jb_user_id])->find();
		    if($jbuser) {
		        $row->jbuser = $jbuser;
		    }
			
			if ($row->type == 1) {
				//$row->trends = \app\common\model\Trends::get($row->trends_id);
				$row->trends = Trends::withTrashed()->where(['id' => $row->trends_id])->find();
			}
		}
		$this->success('请求成功', $list);
	}

	/**
	 * 圈友违规处理详情
	 *  
	 * @ApiMethod (POST)
	 * @param int $id     举报id，必填
	 * @param int $circle_id  圈子id
	 */
	public function ViolationDetail()
	{
		$user_id   = $this->auth->id;
		$id        = $this->request->post('id', 0);
		$circle_id = $this->request->post('circle_id', 0);
		$where = [];
		$where['id'] = $id;
		$detail = Report::where($where)->find();
		if (!$detail) {
			$this->success('信息不存在', [], 2);
		}

		//$detail->visible(['id', 'type', 'circle_id', 'trends_id', 'yuanyin', 'describe', 'ss_describe', 'state', 'jb_state', 'ss_state', 'user', 'jbuser', 'trends']);
		//$detail->getRelation('user')->visible(['nickname', 'avatar']);
		//$detail->getRelation('jbuser')->visible(['nickname', 'avatar']);
		//$detail->user->avatar   = cdnurl($detail->user->avatar, true);
		//$detail->jbuser->avatar = cdnurl($detail->jbuser->avatar, true);
		
	    $user = \app\common\model\User::where(['id'=>$detail->user_id])->find();
		if($user) {
		    $detail->user = $user;
		}
		$jbuser = \app\common\model\User::where(['id'=>$detail->jb_user_id])->find();
		if($jbuser) {
		     $detail->jbuser = $jbuser;
		}
		if ($detail->type == 1) {
			$detail->trends = Trends::withTrashed()->where(['id' => $detail->trends_id])->find();
		}
		$this->success('请求成功', $detail);
	}

	/**
	 * 封禁拉黑列表
	 *  
	 * @ApiMethod (POST)
	 * @param int $type    类型:1=封禁,2=拉黑
	 * @param int $circle_id  圈子id
	 * @param int $page    当前页码
	 * @param int $count   每页数量
	 */
	public function CircleBan()
	{
		$user_id   = $this->auth->id;
		$type      = $this->request->post('type', 0);
		$circle_id = $this->request->post('circle_id', 0);
		$page  = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);

		$where                  = [];
		$where['type']      = $type;
		$where['circle_id'] = $circle_id;

		$list = Ban::where($where)->order('id desc')->paginate($count, false, ["page" => $page]);
		/*foreach ($list as $row) {
			$row->visible(['id', 'type', 'user_id', 'end_time', 'day', 'memo', 'create_time']);
			$row->visible(['user']);
			$row->getRelation('user')->visible(['nickname', 'avatar']);
		}*/
		$this->success('请求成功', $list);
	}

	/**
	 * 解除封禁、拉黑
	 *  
	 * @ApiMethod (POST)
	 * @param int $type    类型，必填（1解除封禁2解除拉黑）
	 * @param string $ids  封禁拉黑信息id，必填（多个id用 , 分隔）
	 */
	public function secure()
	{
		$user_id = $this->auth->id;
		$type    = $this->request->post('type', 0);//1解除封禁2解除拉黑
		$ids     = $this->request->post('ids', '');
		if (empty($type) || empty($ids)) {
			$this->success('参数错误', [], 2);
		}
		$where         = [];
		$where['type'] = $type;
		$where['id']   = ['in', $ids];
		$list = Ban::where($where)->select();
		Db::startTrans();
		$arr = [];
		foreach ($list as $k => $v) {
			$circleuser = CircleUser::get($v->circleuser_id);
			if ($circleuser && $type == 1) {

				if ($circleuser->identity == 0) {
					//不是圈友直接删除记录
					$arr[] = $circleuser->delete();
				} else {
					$arr[] = $circleuser->save(['is_ban' => 2, 'updatetime' => time()]);
				}
				$arr[] = $v->delete();
				//记录圈子日志
				$arr[] = circlelog(1, $user_id, $v->user_id, $v->circle_id, 0, 7);
			} else if ($circleuser && $type == 2) {
//	              if($circleuser->identity == 0){
//		              //不是圈友直接删除记录
//		              $arr[] = $circleuser->delete();
//	              }else{
//		              $arr[] = $circleuser->save(['is_auth'=>1,'updatetime'=>time()]);
//
//	              }
				$arr[] = $circleuser->delete();

				$arr[] = $v->delete();
				//记录圈子日志
				$arr[] = circlelog(1, $user_id, $v->user_id, $v->circle_id, 0, 8);
			}
		}

		if (in_array(false, $arr)) {
			Db::startTrans();
			$this->error("出差了");
		} else {
			Db::commit();
			$this->success('成功');
		}
	}

	/**
	 * 置顶消息
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id  圈子id
	 * @param int $page    当前页码
	 * @param int $count   每页数量
	 */
	public function top_trends()
	{
		$user_id    = $this->auth->id;
		$circle_id  = $this->request->post('circle_id', 1);
		$page       = $this->request->post('page', 1);
		$count      = $this->request->post('count', 10);
		$circles_id = Config::get("site2.ggqz");//公共圈子
		$where              = [];
		$where['is_top']    = 1;
		$where['circle_id'] = $circle_id;

		//$list = \app\common\model\Trends::where($where)->order("id desc")->paginate($count, false, ["page" => $page]);
		$list = Trends::where($where)->order("id desc")->paginate($count, false, ["page" => $page]);
		foreach ($list as $v) {
			$v->append(['userinfo']);
			$v->userinfo = getuser($v, $user_id, $circles_id);
		}

		$this->success("", $list);
	}

	/**
	 * 分区管理
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id  圈子id，必填
	 */
	public function partition()
	{
		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 1);
		if (empty($circle_id)) {
			$this->success('参数错误', [], 2);
		}
		//公共分类
		//$cate = \app\common\model\trends\Cate::select();
		$cate = TrendsCate::select();
		foreach ($cate as $k => $v) {
			//把公共分类添加到我的分类
			$cate2 = Cate2::where(['circle_id' => $circle_id, 'cate_id' => $v->id])->find();
			if (empty($cate2)) {
				Cate2::create([
					              'user_id'    => $user_id,
					              'circle_id'  => $circle_id,
					              'cate_id'    => $v->id,
					              'name'       => $v->name,
					              'weigh'      => $v->weigh,
					              'is_sort'    => 1,
					              'createtime' => time(),
				              ]);
			}
		}
		//调取起的分类
		$list = Cate2::where(['circle_id' => $circle_id])->order("is_sort asc,weigh asc")->select();
		$this->success("", $list);
	}

	/**
	 * 批量排序
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id  圈子id，必填
	 * @param string|array $list 排序字段
	 */
	public function sort()
	{
		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);
		$list      = $this->request->post('list', []);

		$list = json_decode(html_entity_decode($list), true);

		Db::startTrans();
		$arr = [];
		if (count($list) > 0) {

			foreach ($list as $k => $v) {

				$cate = Cate2::where(['circle_id' => $circle_id, 'id' => $v['id']])->find();
				if ($cate) {
					$arr[] = $cate->save(['weigh' => $v['weigh'], 'updatetime' => time()]);
				}
			}

		} else {
			$this->error("参数错误");
		}

		if (in_array(false, $arr)) {
			Db::startTrans();
			$this->error("出差了");
		} else {
			Db::commit();
			$this->success('成功');
		}
	}

	/**
	 * 添加修改分区
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id  圈子id，必填
	 * @param int $cate_id  分类id
	 * @param string $name   分类名称
	 * @param int $weigh   权重
	 * @param int $is_show   开关:1=开,2=关
	 */
	public function add_cate()
	{

		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 1);
		$cate_id   = $this->request->post('cate_id', 0);
		$name      = $this->request->post('name', "");
		$weigh     = $this->request->post('weigh', 0);
		$is_show   = $this->request->post('is_show', 0);

		if (empty($name)) {
			$this->success('请输入分类名称', [], 2);
		}

		$circle = Circle::get($circle_id);

		if (!$circle) {
			$this->success('圈子不存在', [], 2);
		}

		if ($cate_id > 0) {

			$cate = Cate2::get($cate_id);
			if (!$cate) {
				$this->success('分类不存在', [], 2);
			}

			$data = [
				'name' => $name,
			];
			if ($weigh) {
				$data['weigh'] = $weigh;
			}
			if ($is_show) {
				$data['is_show'] = $is_show;
			}

			$res = $cate->save($data);

		} else {

			$res = Cate2::create(['user_id' => $user_id, 'circle_id' => $circle_id, 'name' => $name, 'weigh' => $weigh, 'createtime' => time()]);

		}

		if ($res) {
			$this->success("成功");
		} else {
			$this->error('失败');
		}

	}

	/**
	 * 删除
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id  圈子id，必填
	 * @param int $cate_id  分类id，必填
	 */
	public function del_cate()
	{

		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 1);
		$cate_id   = $this->request->post('cate_id', 0);

		$cate = Cate2::get($cate_id);
		if (!$cate) {
			$this->success('分类不存在', [], 2);
		}

		$trends = Trends::where(['circle_id' => $circle_id, 'cate_id' => $cate_id])->find();
		if ($trends) {
			$this->success('分类存在动态信息不可删除', [], 2);
		}

		$res = $cate->delete();

		if ($res) {
			$this->success("成功");
		} else {
			$this->error('失败');
		}

	}

	/**
	 * 举报处理
	 *  
	 * @ApiMethod (POST)
	 * @param int $type   举报类型，必填 （1=动态举报,2=圈友举报,3=吧主举报,4=管理员举报）
	 * @param int $state  审核状态，必填 （1=举报待处理,2=申诉待处理,3=举报已处理,4=申诉已处理）
	 * @param int $report_id  举报id，必填
	 */
	public function ReportHandle()
	{

		$user_id   = $this->auth->id;
		$nickname  = $this->auth->nickname;
		$type      = $this->request->post('type', '');     //1动态2=圈友,3=吧主,4=管理员
		$state     = $this->request->post('state', '');    //1举报失败2违规警告3移到黑名单4降为圈友5申诉成功6申诉失败
		$report_id = $this->request->post('report_id', '');//举报id

		if (empty($type) || empty($state) || empty($report_id)) {
			$this->success('参数错误', [], 2);
		}

		$report = Report::get($report_id);

		if (!$report) {
			$this->success('举报信息不存在', [], 2);
		}

		Db::startTrans();
		$arr = [];

		if ($state == 1) {//举报失败

			$arr[] = $report->save(['admin_id' => $nickname, 'jb_state' => $state, 'state' => 3, 'jb_cl_time' => time()]);

		} else if ($state == 2) {//违规警告

			$arr[] = $report->save(['admin_id' => $nickname, 'jb_state' => $state, 'state' => 3, 'jb_cl_time' => time()]);
			//动态封禁
			if ($type == 1) {
				$trends = Trends::get($report->trends_id);
				if ($trends) {
					$arr[] = $trends->save(['state' => 2, 'updatetime' => time()]);
					//举报成功奖励
					exps($trends->circle_id, $report->user_id, 11);
				}
			}

		} else if ($state == 3) {//移到黑名单

			$arr[] = $report->save(['admin_id' => $nickname, 'jb_state' => $state, 'state' => 3, 'jb_cl_time' => time()]);

			//移到黑名单代码块
			$circleuser = CircleUser::where(['user_id' => $report->jb_user_id, 'circle_id' => $report->circle_id])->find();
			if ($circleuser) {
				$arr[] = $circleuser->save(['is_auth' => 2, 'identity' => 0, 'updatetime' => time()]);
			} else {
				$arr[] = $circleuser = CircleUser::create(['user_id' => $report->jb_user_id, 'circle_id' => $report->circle_id, 'identity' => 0, 'is_auth' => 2, 'createtime' => time()]);
			}
			//拉黑记录
			//$arr[] = Db::name('circle_ban')->insert([
			$arr[] = \app\common\model\circle\Ban::insert([
				                                        'type'          => 2,
				                                        'circle_id'     => $report->circle_id,
				                                        'circleuser_id' => $circleuser->id,
				                                        'user_id'       => $circleuser->user_id,
				                                        'adminuser_id'  => $user_id,
				                                        'create_time'   => time(),
			                                        ]);
			//动态封禁
			if ($type == 1) {
				$trends = Trends::get($report->trends_id);
				if ($trends) {
					$arr[] = $trends->save(['state' => 2, 'updatetime' => time()]);
					//举报成功奖励
					exps($trends->circle_id, $report->user_id, 11);
				}
			}
		} else if ($state == 4) {//降为圈友

			$arr[] = $report->save(['admin_id' => $nickname, 'jb_state' => $state, 'state' => 3, 'jb_cl_time' => time()]);
			//移到黑名单代码块
			$circleuser = CircleUser::where(['user_id' => $report->jb_user_id, 'circle_id' => $report->circle_id])->find();
			if ($circleuser) {
				$arr[] = $circleuser->save(['y_identity' => $circleuser->identity, 'identity' => 3, 'updatetime' => time()]);
			} else {
				$arr[] = CircleUser::create(['user_id' => $report->jb_user_id, 'circle_id' => $report->circle_id, 'identity' => 3, 'createtime' => time()]);
			}

			//动态封禁
			if ($type == 1) {

				$trends = Trends::get($report->trends_id);
				if ($trends) {
					$arr[] = $trends->save(['state' => 2, 'updatetime' => time()]);
					//举报成功奖励
					exps($trends->circle_id, $report->user_id, 11);
				}
			}

		}

		//添加系统消息 发给举报人的
		$arr[] = Reportlog::create(['user_id' => $report->user_id, 'type' => 1, 'report_id' => $report_id, 'is_see' => 2, 'create_time' => time()]);
		//发给被举报人的
		if ($state > 1) {//举报失败不发送
			$arr[] = Reportlog::create(['user_id' => $report->jb_user_id, 'type' => 2, 'report_id' => $report_id, 'is_see' => 2, 'create_time' => time()]);
			//记录圈子日志
			if ($report->type == 1) {
				$arr[] = circlelog(2, $user_id, $report->jb_user_id, $report->circle_id, $report->trends_id, $state);
			}

		}

		if (in_array(false, $arr)) {
			Db::startTrans();
			$this->error("出差了");
		} else {
			Db::commit();
			$this->success('成功');
		}

	}

	/**
	 * 申诉处理
	 *  
	 * @ApiMethod (POST)
	 * @param int $type   举报类型，必填 （1=动态举报,2=圈友举报,3=吧主举报,4=管理员举报）
	 * @param int $state  审核状态，必填 （1=举报待处理,2=申诉待处理,3=举报已处理,4=申诉已处理）
	 * @param int $report_id  举报id，必填
	 */
	public function AppealHandle()
	{

		$user_id   = $this->auth->id;
		$nickname  = $this->auth->nickname;
		$type      = $this->request->post('type', '');     //1动态2=圈友,3=吧主,4=管理员
		$state     = $this->request->post('state', '');    //1申诉成功2申诉失败
		$report_id = $this->request->post('report_id', '');//举报id

		if (empty($type) || empty($state) || empty($report_id)) {
			$this->success('参数错误', [], 2);
		}

		$report = Report::get($report_id);

		if (!$report) {
			$this->success('举报信息不存在', [], 2);
		}
		if ($report->state != 2) {
			$this->success('用户未提交申诉申请', [], 2);
		}

		Db::startTrans();
		$arr = [];

		if ($state == 1) {//申诉成功

			//举报受理:1=举报失败,2=违规警告,3=移到黑名单,4=降为圈友
			if ($report->jb_state == 3) {//移到黑名单

				$circleuser = CircleUser::where(['user_id' => $report->jb_user_id, 'circle_id' => $report->circle_id])->find();
				if ($circleuser) {
					$arr[] = $circleuser->save(['is_auth' => 1, 'updatetime' => time()]);
				}

			} else if ($report->jb_state == 4) {//降为圈友

				$circleuser = CircleUser::where(['user_id' => $report->jb_user_id, 'circle_id' => $report->circle_id])->find();
				if ($circleuser) {
					$arr[] = $circleuser->save(['identity' => $report->y_identity, 'updatetime' => time()]);
				}

			}

			$arr[] = $report->save(['admin2_id' => $nickname, 'ss_state' => 2, 'state' => 4, 'ss_cl_time' => time()]);
			//动态解除封禁
			if ($type == 1) {

				$trends = Trends::get($report->trends_id);
				if ($trends) {
					$arr[] = $trends->save(['state' => 1, 'updatetime' => time()]);

				}
			}

		} else if ($state == 2) {//申诉失败

			$arr[] = $report->save(['admin_id' => $nickname, 'ss_state' => 3, 'state' => 4, 'ss_cl_time' => time()]);

		}

		//添加系统消息
		//发给被举报人的
		$arr[] = Reportlog::create(['user_id' => $report->jb_user_id, 'type' => 3, 'report_id' => $report_id, 'is_see' => 2, 'create_time' => time()]);

		if (in_array(false, $arr)) {
			Db::startTrans();
			$this->error("出差了");
		} else {
			Db::commit();
			$this->success('成功');
		}

	}

	/**
	 * 修改圈子信息
	 *  
	 * @ApiMethod (POST)
	 * @param int $type   类型，必填 （1修改logo，2修改角色名称,3修改背景图）
	 * @param int $circle_id  圈子id，必填
	 */
	public function save_circle()
	{
		$param     = $this->request->param();
		$type      = $this->request->post('type');//1修改logo，2修改角色叫法,3背景图
		$circle_id = $this->request->post('circle_id', 0);

		if ($type == 1) {
			$this->rule = [
				"logo_image|Logo" => ["require"],

			];
		} else if ($type == 2) {
			$this->rule = [
				"quanyou|圈友" => ["require"],
				"bazhu|吧主"   => ["require"],
				"admin|管理员" => ["require"],
			];
		} else if ($type == 3) {
			$this->rule = [
				"image|背景图" => ["require"],

			];
		} else {

			$this->error("出差了");
		}

		$this->checks($param);

		if ($circle_id > 0) {

			$circle = \app\common\model\Circle::get($circle_id);
			if (!$circle) {
				$this->success('信息不存在', [], 2);
			}
			if ($type == 1 && $circle->logo_image != $param['logo_image']) {

				$times = time() - $circle->logo_time;
				$day   = $times / (3600 * 24);

				if ($day < 90) {
					$this->success('3个月内只能修改一次', [], 2);
				}
				$param["logo_time"] = time();

			} else if ($type == 3 && $circle->image != $param['image']) {

				$times = time() - $circle->image_time;
				$day   = $times / (3600 * 24);

				if ($day < 15) {
					$this->success('15天内只能修改一次', [], 2);
				}
				$param["image_time"] = time();

			}
			unset($param["type"], $param["circle_id"]);
			$res = $circle->save($param);

		} else {

			$this->error("出差了");
		}

		if ($res) {

			$this->success('提交成功');
		} else {
			$this->error("出差了");
		}
	}

	/**
	 * 发布公告
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id  圈子id，必填
	 * @param int $content   公告内容
	 * @return void
	 */
	public function add_notice()
	{
		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', '');
		$content   = $this->request->post('content', '');

		$circle = Circle::get($circle_id);

		if (!$circle) {
			$this->success('圈子不存在', [], 2);
		}
		$tan = Config::get("site.tan");
		if ($content == $tan) {
			$this->success('未做任何修改', [], 2);
		}
		if ($content != $circle->notice) {
			$notice = Notice::where(['circle_id' => $circle_id, 'status' => 1])->find();
			if ($notice) {
				$this->success('有未审核的公告，审核后才可继续发布', [], 2);
			}
			$res = Notice::create(['user_id' => $user_id, 'circle_id' => $circle_id, 'content' => $content, 'createtime' => time()]);
		} else {
			$this->success('未做任何修改', [], 2);
		}
		if ($res) {
			$this->success('成功');
		} else {
			$this->error('出差了');
		}
	}

	/**
	 * 圈子数据
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id  圈子id，必填
	 */
	public function circle_data()
	{
		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', '');

		$data = [];
		//圈子总人数
		//$data['circle_num'] = Db::name('circle_user')->where(['circle_id' => $circle_id, 'identity' => ['lt', 4]])->count();
		$data['circle_num'] = CircleUser::where(['circle_id' => $circle_id, 'identity' => ['lt', 4]])->count();
		//圈子总动态
		//$data['trends_num'] = Db::name('trends')->where(['circle_id' => $circle_id, 'state' => 1, 'is_draft' => 2, 'state' => 1])->count();
		$data['trends_num'] = Trends::where(['circle_id' => $circle_id, 'state' => 1, 'is_draft' => 2, 'state' => 1])->count();
		//昨日新增成员
		//$data['user_num'] = Db::name("circle_user")->where(['circle_id' => $circle_id, 'identity' => ['lt', 4]])->whereTime('createtime', 'yesterday')->count();
		$data['user_num'] = CircleUser::where(['circle_id' => $circle_id, 'identity' => ['lt', 4]])->whereTime('createtime', 'yesterday')->count();
		//昨日新增动态
		//$data['add_trends_num'] = Db::name("trends")->where(['circle_id' => $circle_id, 'state' => 1, 'is_draft' => 2])->whereTime('create_time', 'yesterday')->count();
		$data['add_trends_num'] = Trends::where(['circle_id' => $circle_id, 'state' => 1, 'is_draft' => 2])->whereTime('create_time', 'yesterday')->count();
		//昨日登录人数
		$data['ren_num'] = Db::connect($this->connection)->name("circle_accesslog")->where(['circle_id' => $circle_id])->whereTime('createtime', 'yesterday')->count();
		//昨日新增评论数
		//$data['comment_num'] = Db::name("trends_comment")->where(['type' => 1, 'circle_id' => $circle_id])->whereTime('create_time', 'yesterday')->count();
		$data['comment_num'] = TrendsComment::where(['type' => 1, 'circle_id' => $circle_id])->whereTime('create_time', 'yesterday')->count();
		//昨日转发数
		$data['forward_num'] = 0;
		//昨日点赞数
		//$data['like_num'] = Db::name("publics_likecoll")->where(['type' => ['in', '1,3'], 'circle_id' => $circle_id])->whereTime('createtime', 'yesterday')->count();
		$data['like_num'] = Likecoll::where(['type' => ['in', '1,3'], 'circle_id' => $circle_id])->whereTime('createtime', 'yesterday')->count();
		//最近7天新增圈友

		$column    = [];
		$starttime = Date::unixtime('day', -6);
		$endtime   = Date::unixtime('day', 0, 'end');
		$joinlist  = CircleUser::where(['identity' => ['in', '1,2,3']])->where('createtime', 'between time', [$starttime, $endtime])
		                              ->field('createtime, COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(createtime), "%m-%d") AS join_date')
		                              ->group('join_date')
		                              ->select();
		for ($time = $starttime; $time <= $endtime;) {
			$column[] = date("m-d", $time);
			$time     += 86400;
		}
		$userlist = array_fill_keys($column, 0);
		foreach ($joinlist as $k => $v) {
			$userlist[$v['join_date']] = $v['nums'];
		}
		$data['user_list'] = $userlist;
		$this->success('成功', $data);
	}

	/**
	 * 圈子日志
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id  圈子id，必填
	 * @param int $type  日志类型:1=圈子,2=动态
	 * @param int $page  当前页码
	 * @param int $count 每页数据
	 */
	public function circle_log()
	{
		$user_id   = $this->auth->id;
		$circle_id = $this->request->post('circle_id', '');
		$type      = $this->request->post('type', 1);
		$page      = $this->request->post('page', 1);
		$count     = $this->request->post('count', 10);

		$where                  = [];
		$where['circle_id'] = $circle_id;
		$where['type']      = $type;

		$list = CircleLog::where($where)->order('id desc')
		                                ->paginate($count, false, ["page" => $page]);
		foreach ($list as $row) {
		    $user = \app\common\model\User::where(['id'=>$row->user_id])->find();
		    if($user) {
		        $row->user = $user;
		    }
		    $user2 = \app\common\model\User::where(['id'=>$row->user2_id])->find();
		    if($user2) {
		        $row->user2 = $user2;
		    }
		    $trends = \app\common\model\Trends::where(['id'=>$row->trends_id])->find();
		    if($trends) {
		        $row->trends = $trends;
		    }
		}

		$this->success('成功', $list);
	}

	/**
	 * 获取本圈子公告
	 *  
	 * @ApiMethod (POST)
	 * @param int $circle_id  圈子id，必填
	 */
	public function get_notice()
	{
		$circle_id = $this->request->post('circle_id', 0);
		$notice = Notice::where(['circle_id' => $circle_id])->order('id desc')->find();
		if ($notice) {
			$this->success('成功', $notice);
		} else {
			$this->success('成功', ['content' => Config::get("site2.tan")], 2);
		}
	}

	/**
	 * 加群文案信息
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 */
	public function group_info()
	{
		$circle_id = $this->request->post('circle_id', 0);
		if (!$circle_id) {
			$this->success('参数错误', [], 2);
		}

		$where              = [];
		$where['circle_id'] = $circle_id;
		$where['is_show']   = 1;
		$where['status']    = 2;
		$group = array();
		//$group = \app\common\model\trends\Group::where($where)->find();
		$this->success("加群文案信息", $group);
	}
}
